'''
# -*- coding:utf-8 -*-
# @Project: DevOps_api
# @Date: 2023/3/26 - 18:21
# @Author: ysg
# @Describe: 

update_zip.py
'''
import os
import shutil
import sys

target_path = sys.argv[1]
ver_name = sys.argv[2]

# target_path = r'E:\copy_test2'
# ver_name = '000212'
source_path = '/ysg/back_up/back/'
back_path = '/ysg/back_up/'


def copy_dir():
    '''
    上传到 /ysg/back_up/back.zip 下的文件为 source_path  dirpath_old  filepath_old
    覆盖到指定目录的路径为 target_path  dirpath_new  filepath_new
    :return:
    '''
    back_ver_dir = os.path.join(back_path, ver_name)
    back_ver_file = os.path.join(back_path, ver_name + '.ver')
    os.mkdir(back_ver_dir)
    if not os.path.isdir(source_path):
        os.mkdir(source_path)
    fw = open(back_ver_file, 'w', encoding='utf-8')
    fw.write(target_path + '\n')
    if not os.path.isdir(target_path):
        return '输入的路径不是目录'
    for root, directories, files in os.walk(source_path):
        for dirname in directories:
            dirpath_old = os.path.join(root, dirname)
            dirpath_new = dirpath_old.replace(source_path, target_path, 1)
            if not os.path.isdir(dirpath_new):
                fw.write(f'{dirpath_new}||False' + '\n')
                os.makedirs(dirpath_new)
            else:
                # 备份被覆盖的目录
                dirpath_back = dirpath_old.replace(source_path, back_ver_dir + '/', 1)
                if not os.path.isdir(dirpath_back):
                    os.makedirs(dirpath_back)
                fw.write(f'{dirpath_new}||True' + '\n')

        for filename in files:
            filepath_old = os.path.join(root, filename)
            filepath_new = filepath_old.replace(source_path, target_path, 1)
            if os.path.isfile(filepath_new):
                fw.write(f'{filepath_new}||True' + '\n')
                # 备份被覆盖的文件
                filepath_back = filepath_old.replace(source_path, back_ver_dir + '/', 1)
                shutil.copy(filepath_new, filepath_back)
            else:
                fw.write(f'{filepath_new}||False' + '\n')
            shutil.copy(filepath_old, filepath_new)

    print(f'{ver_name}：上传完成')
    fw.close()


copy_dir()
